package com.zhangyujun.bysj.manager.service.impl;

import cn.hutool.core.date.DateUtil;
import com.zhangyujun.bysj.common.exception.GuiguException;
import com.zhangyujun.bysj.manager.service.FileUploadService;
import com.zhangyujun.bysj.model.vo.common.ResultCodeEnum;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;
import java.util.UUID;


@Service
public class FileUploadServiceImpl implements FileUploadService {
    //minio服务器地址
    @Value("${bysj.minio.endpointUrl}")
    private String endpointUrl;
    //minio用户名
    @Value("${bysj.minio.accessKey}")
    private String accessKey;
    //minio密码
    @Value("${bysj.minio.secreKey}")
    private String secreKey;
    //bucket名
    @Value("${bysj.minio.bucketName}")
    private String bucketName;
    @Override
    public String upload(MultipartFile file) {
        try {
            // 创建MinioClient对象.
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpointUrl)
                    .credentials(accessKey, secreKey)
                    .build();
            // 创建一个bucket
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            // 如果不存在，那么此时就创建一个新的桶
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            } else {  // 如果存在打印信息
                System.out.println("Bucket 'bysj-bucket' already exists.");
            }
            // 获取上传文件名称
            //1 让每个上传文件的名称是唯一的，  uuid 成成 01.jpg
            //2 根据当前日期对上传文件进行分组
            String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = dateDir + "/" + uuid + file.getOriginalFilename();
            // 文件上传
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName)
                            .object(fileName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .build());

            // 获取上传文件在minio的路径
            String url = endpointUrl + "/" + bucketName + "/" + fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuiguException(ResultCodeEnum.SYSTEM_ERROR);
        }
    }
}
